﻿#include <iostream>
#include <sstream>
#include "custom_data.h"

using namespace boost::interprocess;

custom_data::custom_data() {

}

void custom_data::init(managed_shared_memory& segment) {
    a_ptr_ = segment.construct<int>("custom_data_a_ptr")(0);
    *a_ptr_ = 0;
    a_mutex_ptr_ = segment.construct<interprocess_mutex>("custom_data_a_mutex_ptr")();

    const shmem_allocator alloc_inst (segment.get_segment_manager());
    b_ptr_ = segment.construct<my_vector>("custom_data_b_ptr")(alloc_inst);
    b_mutex_ptr_ = segment.construct<interprocess_mutex>("custom_data_b_mutex_ptr")();
}

void custom_data::add() {
    scoped_lock<interprocess_mutex> lock(*a_mutex_ptr_);
    (*a_ptr_)++;
}

void custom_data::push_back(int num) {
    scoped_lock<interprocess_mutex> lock(*b_mutex_ptr_);
    b_ptr_->push_back(num);
}

void custom_data::print() {
    std::cout << "a_ptr:" << *a_ptr_ << std::endl;
    std::cout << "b_ptr size:" << b_ptr_->size() << std::endl;
    std::ostringstream oss;
    int cnt = 0;
    for (auto it = b_ptr_->begin(); it != b_ptr_->end() && cnt < 200; ++it) {
        oss << *it << ",";
        cnt++;
    }
    std::cout << oss.str() << std::endl;
}